package com.yaoweigroup.community.ui.home;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.adapter.GroupAdapter;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.enity.Group;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.UtilHttp;

/**
 * 团购
 * 
 * @author xi
 * 
 */
public class GroupActivity extends Activity implements OnClickListener {

	private PullToRefreshListView listView;
	private GroupAdapter adapter;
	private List<Group> list;

	private RelativeLayout left_rl;
	private ObjectMapper mapper;

	public final int OBTAIN_SUCCESS = 0x2210;
	public final int OBTAIN_FAIL = OBTAIN_SUCCESS + 1;

	private ProgressBar progress;
	private boolean isLoadEnd = false;
	private ImageView error_iv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_group);

		error_iv = (ImageView) findViewById(R.id.error_iv);
		progress = (ProgressBar) findViewById(R.id.progress);
		mapper = new ObjectMapper();
		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);
		list = new ArrayList<Group>();
		adapter = new GroupAdapter(this, list);
		listView = (PullToRefreshListView) findViewById(R.id.listView);
		listView.setAdapter(adapter);

		listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(
						getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);

				progress.setVisibility(View.GONE);
				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				// Do work to refresh the list here.
				error_iv.setVisibility(View.GONE);
				pageNo = 1;
				list.clear();
				obtainData();
			}
		});

		listView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

			@Override
			public void onLastItemVisible() {
				if (isLoadEnd) {
					return;
				}
				obtainData();
			}
		});
		obtainData();
	}

	private int pageNo = 1;
	private int pageSize = 10;
	private List<Group> groups;

	private void obtainData() {
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("pageNo", pageNo + "");
		jsonUtil.add("pageSize", pageSize + "");
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getGroupBy, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							if (state == 200) {
								groups = mapper.readValue(data,
										new TypeReference<List<Group>>() {
										});
								handler.sendEmptyMessage(OBTAIN_SUCCESS);
							} else {
								handler.sendEmptyMessage(OBTAIN_FAIL);

							}
						} catch (Exception e) {
							handler.sendEmptyMessage(OBTAIN_FAIL);
							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(OBTAIN_FAIL);

					}

				});
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			progress.setVisibility(View.GONE);
			switch (msg.what) {
			case OBTAIN_FAIL:

				if (list.size() == 0)
					error_iv.setVisibility(View.VISIBLE);
				break;
			case OBTAIN_SUCCESS:
				if (groups != null && groups.size() > 0) {
					list.addAll(groups);
					adapter.setDataChange(list);
					if (groups.size() < pageSize) {
						isLoadEnd = true;
					} else {
						pageNo += 1;
						isLoadEnd = false;
					}
					if (list.size() == 0) {
						error_iv.setVisibility(View.VISIBLE);
					}
					listView.onRefreshComplete();
				}
				break;
			}
		};
	};

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_rl:
			finish();
			break;
		}
	}

}
